﻿using System;
using System.IO;

namespace ProjectN.Core
{
    public class TempDirectory : IDisposable
    {
        private DirectoryInfo? directory;

        private static string NewTempPath(string prefix) => Path.Combine(Path.GetTempPath(), prefix + Guid.NewGuid().ToString());

        private bool disposedValue;
        public void Dispose()
        {
            if (!disposedValue)
            {
                directory?.Delete(true);
                directory = null;

                disposedValue = true;
                GC.SuppressFinalize(this);
            }
        }

        public TempDirectory(string? prefix = null)
        {
            string path = NewTempPath(prefix ?? "");
            while (System.IO.Directory.Exists(path))
                path = NewTempPath(prefix ?? "");
            directory = System.IO.Directory.CreateDirectory(path);
        }

        public DirectoryInfo Directory
        {
            get
            {
                ObjectDisposedException.ThrowIf(directory == null, nameof(TempDirectory));
                return directory;
            }
        }

        public static implicit operator DirectoryInfo(TempDirectory tempDir) => tempDir.Directory;

    }
}
